package com.wsjzzcbq.qianyuan.sys.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wsjzzcbq.qianyuan.common.cache.CacheService;
import com.wsjzzcbq.qianyuan.common.constant.CacheConsts;
import com.wsjzzcbq.qianyuan.common.constant.SysConsts;
import com.wsjzzcbq.qianyuan.common.util.CookieUtils;
import com.wsjzzcbq.qianyuan.sys.bean.Menu;
import com.wsjzzcbq.qianyuan.sys.bean.SysRolePermission;
import com.wsjzzcbq.qianyuan.sys.mapper.SysRolePermissionMapper;
import com.wsjzzcbq.qianyuan.sys.service.MenuService;
import com.wsjzzcbq.qianyuan.sys.service.SysRolePermissionService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;

/**
 * SysRolePermissionImpl
 *
 * @author wsjz
 * @date 2022/03/12
 */
@Service
public class SysRolePermissionImpl extends ServiceImpl<SysRolePermissionMapper, SysRolePermission> implements SysRolePermissionService {

    @Autowired
    private MenuService menuService;

    @Autowired
    private CacheService cacheService;

    @Override
    public JSONArray findMenuByRoleId(Long roleId) {
        LambdaQueryWrapper<SysRolePermission> lqw = new LambdaQueryWrapper<>();
        lqw.eq(SysRolePermission::getRoleId, roleId);
        lqw.select(SysRolePermission::getMenuId);
        List<Long> meunIds = this.list(lqw).stream().map(SysRolePermission::getMenuId).collect(Collectors.toList());

        List<Menu> list = menuService.listByIds(meunIds);

        //添加用户权限
        String[] permissions =  list.parallelStream().map(Menu::getName).filter(v->StringUtils.isNotBlank(v)).distinct().toArray(String[]::new);
        String token = CookieUtils.getValyeByName(SysConsts.COOKIE_TOKEN);
        cacheService.setSet(CacheConsts.permissionKey(token), permissions);

        return menuService.menu(list);
    }
}
